<?php
require_once "config.php";

class Connection{
	
	public function __construct() {
		//資料庫設定
	    //資料庫位置
	    $db_server = "localhost";
	    //資料庫名稱
	    $db_name = "ulikewall";
	    //資料庫管理者帳號
	    $db_user = "root";
	    // 資料庫管理者密碼
	    $db_passwd = "";
	        
	    //對資料庫連線
	    if (!@mysql_connect($db_server, $db_user, $db_passwd))
	        die("無法對資料庫連線");
	        
	    //資料庫連線採UTF8
	    //mysql_query("SET NAMES utf8");
	        
	    //選擇資料庫
	    if (!@mysql_select_db($db_name))
	        die("無法使用資料庫");
		
	}
	public function addSubscription($new_url,$new_title){
		$uid = $_SESSION['LOGIN_INFO']['id'];
		
		$category = $this->fetchCategory($uid);
		
		if(!$category){
			$this->addEmptyCategory($uid);
			$category = $this->fetchCategory($uid);
		}
		
		
		$category = urldecode($category);
		$category = json_decode($category, true);
		$category_counts = count($category)-1;
		
		$sub_categories = $this->fetchSubCategory($uid);
		
		if(!$sub_categories){
			//return array('update_status'=>false,'msg'=>'子分類不可為空');
			$this->addEmptySubCategory($uid);
			$sub_categories = $this->fetchSubCategory($uid);
		}
		
		$sub_categories = urldecode($sub_categories);
		$sub_categories = json_decode($sub_categories, true);
		$sub_categories_counts = count($sub_categories[$category_counts]);
		//return  $sub_categories_counts;
		/*
		 * 將新增分類放到：未分類
		 */
		
		$sub_categories[$category_counts][$sub_categories_counts]['title'] = $new_title;
		$sub_categories[$category_counts][$sub_categories_counts]['url'] = $new_url;
		//$utf8_sub_category = $this->big5ToUtf8($sub_categories);
		$json_encoded_sub_category = json_encode($sub_categories);
		$json_encoded_sub_category = urlencode($json_encoded_sub_category);
		mysql_query(sprintf('UPDATE `sub_category` SET `sub_category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_sub_category,$uid));
		if(mysql_affected_rows()>0){
			return array('update_status'=>true,'msg'=>'新增成功');
		}
		else{
			return array('update_status'=>false,'msg'=>'更新失敗');
		}
	}
	
	public function addCategory($new_category){
		$uid = $_SESSION['LOGIN_INFO']['id'];
		
		/*
		 * 新增分類的array 的開頭
		 */
		$category = $this->fetchCategory($uid);
		if(!$category){
			$this->addEmptyCategory($uid);
			$category = $this->fetchCategory($uid);
		}
		$category = urldecode($category);
		$category = json_decode($category, true);
		array_unshift($category,$new_category);
		
		
		/*
		 * 新增一個空的子分類到新分類裡
		 */
		$sub_categories = $this->fetchSubCategory($uid);
		
		if(!$sub_categories){
			//return array('update_status'=>false,'msg'=>'子分類不可為空');
			$this->addEmptySubCategory($uid);
			$sub_categories = $this->fetchSubCategory($uid);
		}
		
		$sub_categories = urldecode($sub_categories);
		$sub_categories = json_decode($sub_categories, true);
		array_unshift($sub_categories,array());
		
		
		//$utf8_sub_category = $this->big5ToUtf8($sub_categories);
		$json_encoded_category = json_encode($category);
		$json_encoded_category = urlencode($json_encoded_category);
		mysql_query(sprintf('UPDATE `category` SET `category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_category,$uid));
		if(mysql_affected_rows()==0){
			return array('update_status'=>false,'msg'=>'更新失敗');
		}
		
		$json_encoded_sub_category = json_encode($sub_categories);
		$json_encoded_sub_category = urlencode($json_encoded_sub_category);
		mysql_query(sprintf('UPDATE `sub_category` SET `sub_category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_sub_category,$uid));
		if(mysql_affected_rows()>0){
			return array('update_status'=>true,'msg'=>'新增成功');
		}
		else{
			return array('update_status'=>false,'msg'=>'更新失敗');
		}
		
	}
	
	public function addEmptyCategory($uid){
		$empty_categories = array('未分類');
		
		//$utf8_categories = $this->big5ToUtf8(&$default_categories);
		$json_encoded_category = json_encode($empty_categories);
		$json_encoded_category = urlencode($json_encoded_category);
		
		
		mysql_query(sprintf('INSERT INTO `category` (`uid`,`category`) values (\'%s\',\'%s\')',$uid,$json_encoded_category));
		$category_id = mysql_insert_id();
		
		mysql_query(sprintf('UPDATE `user_info` SET `category`="%s" WHERE `uid`="%s"',$category_id,$uid));
		
		if(mysql_errno()==0){
			return true;
		}
		else{
			return false;
		}
	}
	
	public function addEmptySubCategory($uid){
		$empty_sub_categories = array(array());
		
		//$utf8_categories = $this->big5ToUtf8(&$default_categories);
		$json_encoded_sub_category = json_encode($empty_sub_categories);
		$json_encoded_sub_category = urlencode($json_encoded_sub_category);
		
		
		mysql_query(sprintf('INSERT INTO `sub_category` (`uid`,`sub_category`) values (\'%s\',\'%s\')',$uid,$json_encoded_category));
		$sub_category_id = mysql_insert_id();
		
		mysql_query(sprintf('UPDATE `user_info` SET `sub_category`="%s" WHERE `uid`="%s"',$sub_category_id,$uid));
		
		if(mysql_errno()==0){
			return true;
		}
		else{
			return false;
		}
	}
	
	public function deleteSubscription($category_id,$sub_category_id){
		
		$sub_categories = $this->fetchSubCategory($_SESSION['LOGIN_INFO']['id']);
		$uid = $_SESSION['LOGIN_INFO']['id'];
		$sub_categories = urldecode($sub_categories);
		$sub_categories = json_decode($sub_categories, true);
		
		/*
		 * unset 後要重新排序
		 */
		unset($sub_categories[$category_id][$sub_category_id]);
		$sub_categories[$category_id] = array_values($sub_categories[$category_id]);
		
		$json_encoded_sub_category = json_encode($sub_categories);
		$json_encoded_sub_category = urlencode($json_encoded_sub_category);
		mysql_query(sprintf('UPDATE `sub_category` SET `sub_category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_sub_category,$uid));
		if(mysql_affected_rows()>0){
			return array('delete_status'=>true);
		}
		else{
			return array('delete_status'=>false);
		}
	}
	
	public function deleteCategory($category_id){
		/*
		 * 先把要被刪分類裡的訂閱移到未分類,再刪除分類
		 */
		$sub_categories = $this->fetchSubCategory($_SESSION['LOGIN_INFO']['id']);
		$uid = $_SESSION['LOGIN_INFO']['id'];
		$sub_categories = urldecode($sub_categories);
		$sub_categories = json_decode($sub_categories, true);
		$the_uncategory_index = count($sub_categories)-1;
		$sub_categories[$the_uncategory_index] = array_merge($sub_categories[$the_uncategory_index],$sub_categories[$category_id]);
		unset($sub_categories[$category_id]);
		$sub_categories = array_values($sub_categories);
		
		$json_encoded_sub_category = json_encode($sub_categories);
		$json_encoded_sub_category = urlencode($json_encoded_sub_category);
		mysql_query(sprintf('UPDATE `sub_category` SET `sub_category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_sub_category,$uid));
		
		
		$categories = $this->fetchCategory($_SESSION['LOGIN_INFO']['id']);
		
		$categories = urldecode($categories);
		$categories = json_decode($categories, true);
		
		/*
		 * unset 後要重新排序
		 */
		unset($categories[$category_id]);
		$categories = array_values($categories);
		
		$json_encoded_category = json_encode($categories);
		$json_encoded_category = urlencode($json_encoded_category);
		mysql_query(sprintf('UPDATE `category` SET `category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_category,$uid));
		if(mysql_affected_rows()>0){
			return array('delete_status'=>true,'msg'=>'刪除成功');
		}
		else{
			return array('delete_status'=>false,'msg'=>'刪除失敗');
		}
	}
	
	public function changeCategory($category_id,$sub_category_id,$new_category_id){
		/*
		 * first: move to new category
		 */
		$sub_categories = $this->fetchSubCategory($_SESSION['LOGIN_INFO']['id']);
		$uid = $_SESSION['LOGIN_INFO']['id'];
		$sub_categories = urldecode($sub_categories);
		$sub_categories = json_decode($sub_categories, true);
		$sub_categories_counts = count($sub_categories[$category_id]);
		$new_val = array('title'=>$sub_categories[$category_id][$sub_category_id]['title'],'url'=>$sub_categories[$category_id][$sub_category_id]['url']);
		
		/*
		 * 如果這個陣列不存在就新增陣列
		 */
		if(!is_array($sub_categories[$new_category_id])){
			$sub_categories[$new_category_id] = array();
		}
		
		array_push($sub_categories[$new_category_id], $new_val);
		
		/*
		 * second: delete the original subscription
		 * unset 後要重新排序
		 */
		unset($sub_categories[$category_id][$sub_category_id]);
		$sub_categories[$category_id] = array_values($sub_categories[$category_id]);
		$json_encoded_sub_category = json_encode($sub_categories);
		$json_encoded_sub_category = urlencode($json_encoded_sub_category);
		mysql_query(sprintf('UPDATE `sub_category` SET `sub_category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_sub_category,$uid));
		if(mysql_affected_rows()>0){
			return array('update_status'=>true);
		}
		else{
			return array('update_status'=>false);
		}
	}
	
	
	public function renameTitle($category_id,$sub_category_id,$new_title){
		
		$sub_categories = $this->fetchSubCategory($_SESSION['LOGIN_INFO']['id']);
		$uid = $_SESSION['LOGIN_INFO']['id'];
		$sub_categories = urldecode($sub_categories);
		$sub_categories = json_decode($sub_categories, true);
		
		//echo "<pre>";print_r();echo"</pre>";
		$sub_categories[$category_id][$sub_category_id]['title'] = $new_title;
		//$utf8_sub_category = $this->big5ToUtf8($sub_categories);
		$json_encoded_sub_category = json_encode($sub_categories);
		$json_encoded_sub_category = urlencode($json_encoded_sub_category);
		mysql_query(sprintf('UPDATE `sub_category` SET `sub_category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_sub_category,$uid));
		if(mysql_affected_rows()>0){
			return array('update_status'=>true,'new_title'=>$new_title);
		}
		else{
			return array('update_status'=>false,'new_title'=>$new_title);
		}
	}
	
	public function renameCategoryTitle($category_id,$new_title){
		
		$categories = $this->fetchCategory($_SESSION['LOGIN_INFO']['id']);
		$uid = $_SESSION['LOGIN_INFO']['id'];
		$categories = urldecode($categories);
		$categories = json_decode($categories, true);
		
		$categories[$category_id] = $new_title;
		
		$json_encoded_category = json_encode($categories);
		$json_encoded_category = urlencode($json_encoded_category);
		mysql_query(sprintf('UPDATE `category` SET `category`=\'%s\' WHERE `uid`=\'%s\'',$json_encoded_category,$uid));
		if(mysql_affected_rows()>0){
			return array('update_status'=>true,'new_title'=>$new_title);
		}
		else{
			return array('update_status'=>false,'new_title'=>$new_title);
		}
	}
	
	public function	checkIfUserSetUp($uid){
		$query=sprintf('SELECT * FROM `user_info` WHERE `uid` = "%s" ',$uid);
		$result = mysql_query($query);
		
		if(mysql_num_rows($result)==0){
			/*
			 * 表示user是第一次登入
			 * 所以要先塞default category
			 */
			
			if($this->setUpUserDefaultData($uid)){
				return true;	
			}
			else{
				return false;	
			}
		}
		else{
			return false;
		}
	}
	
	public function setUpUserDefaultData($uid){
		global $default_categories;
		global $default_sub_category;
		
		//$utf8_categories = $this->big5ToUtf8(&$default_categories);
		$json_encoded_category = json_encode($default_categories);
		$json_encoded_category = urlencode($json_encoded_category);
		
		//$utf8_sub_category = $this->big5ToUtf8(&$default_sub_category);
		$json_encoded_sub_category = json_encode($default_sub_category);
		$json_encoded_sub_category = urlencode($json_encoded_sub_category);
		
		mysql_query(sprintf('INSERT INTO `category` (`uid`,`category`) values (\'%s\',\'%s\')',$uid,$json_encoded_category));
		$category_id = mysql_insert_id();
		
		mysql_query(sprintf('INSERT INTO `sub_category` (`uid`,`sub_category`) values (\'%s\',\'%s\')',$uid,$json_encoded_sub_category));
		$sub_category_id = mysql_insert_id();
		
		mysql_query(sprintf('INSERT INTO `user_info` (`uid`,`category`,`sub_category`) values (\'%s\',\'%s\',\'%s\')',$uid,$category_id,$sub_category_id));
		
		if(mysql_errno()==0){
			return true;
		}
		else{
			return false;
		}
	}
	
	public function big5ToUtf8($arr){
		foreach($arr as $key=>$val){
			if(is_array($val)){
				/*
				 * for recusive array
				 */ 
				return $this->big5ToUtf8($val);
			}
			else{
				if(mb_detect_encoding($val) != 'UTF-8'){
					$arr[$key] = addslashes(mb_convert_encoding($val,"UTF-8","big5"));
				}	
				
				//$arr[$key] = urlencode($arr[$key]);
			}
		}
		
		return $arr;
	}
	
	public function fetchCategory($uid){
		$result = mysql_query(sprintf('SELECT * FROM `category` WHERE `uid`=\'%s\'',$uid));
		if(mysql_num_rows($result)==0){
			return false;
		}
		
		$row = mysql_fetch_assoc($result);
		$json_category = $row['category'];
		return $json_category;
	}
	
	public function fetchSubCategory($uid){
		$result = mysql_query(sprintf('SELECT * FROM `sub_category` WHERE `uid`=\'%s\'',$uid));
		if(mysql_num_rows($result)==0){
			return false;
		}
		
		$row = mysql_fetch_assoc($result);
		$json_sub_category = $row['sub_category'];
		return $json_sub_category;
	}

}


?>